package 面试代码;

/**
 * 还可以使用LockSupport的方式
 */
public class 线程交替打印 {
    public static void main(String[] args) {
        Object o = new Object();
        char[] arr1 = "1234567".toCharArray();
        char[] arr2 = "ABCDEFG".toCharArray();
        Thread t1 = new Thread(){
            @Override
            public void run() {
                synchronized (o) {
                    for (char c : arr1) {
                        System.out.print(c);
                        try {
                            o.notify();
                            o.wait(); //让出锁
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    o.notify(); //必须，否则无法停止程序
                }
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                synchronized (o) {
                    for (char c : arr2) {
                        System.out.print(c);
                        try {
                            o.notify();
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    o.notify();
                }
            }
        };
        t1.start();
        t2.start();
    }
}
